import { HttpException, HttpStatus, Injectable } from '@nestjs/common';
import { CreateGoodsCategoryDto } from './dto/create-goods-category.dto';
import { IsNull, Not, Repository } from 'typeorm';
import { GoodsCategory } from './entities/goods-category.entity';
import { InjectRepository } from '@nestjs/typeorm';

@Injectable()
export class GoodsCategoryService {
  constructor(
      @InjectRepository(GoodsCategory)
      private readonly goodsCategoryRepository: Repository<GoodsCategory>,
      //@Inject(CACHE_MANAGER) private readonly cacheManager: Cache
    ) {}
  async isCateExists(where){
    const result = await this.goodsCategoryRepository.findOne({where});
    return !!result
  }
  
  async save(createGoodsCategoryDto: CreateGoodsCategoryDto) {
    try{
      let where = {}
      if(createGoodsCategoryDto.id){
        where = {id: Not(createGoodsCategoryDto.id)}
      }
      //验证名称重复
      const isNameExists = await this.isCateExists({
        ...where,
        name: createGoodsCategoryDto.name
      })
      if(isNameExists){
        throw new HttpException('分类名称不可重复', HttpStatus.INTERNAL_SERVER_ERROR);
      }
      //验证编码重复
      const isCodeExists = await this.isCateExists({
        ...where,
        code: createGoodsCategoryDto.code
      })
      if(isCodeExists){
        throw new HttpException('分类编码不可重复', HttpStatus.INTERNAL_SERVER_ERROR);
      }
    
      return await this.goodsCategoryRepository.save({
        ...createGoodsCategoryDto,
        parentId: createGoodsCategoryDto.parentId || 0,
      })
    } catch (error) {
      throw new HttpException(error.message, error.status, {
        cause: error
      });
    }
  }

  async findAll() {
    try {
      return await this.goodsCategoryRepository.find({
        select: ['id', 'name', 'status', 'parentId', 'description','code', 'deletedTime'],
      });
    } catch (error) {
      throw new HttpException(error, HttpStatus.INTERNAL_SERVER_ERROR);
    }
  }

  findOne(id: number) {
    return `This action returns a #${id} goodsCategory`;
  }

  async delete(id: string) {
    try {
      return await this.goodsCategoryRepository.delete(id);
    } catch (error) {
      throw new HttpException(error, HttpStatus.INTERNAL_SERVER_ERROR);
    }
  }

  async remove(id: string) {
    try {
      return await this.goodsCategoryRepository.softDelete(id);
    } catch (error) {
      throw new HttpException(error, HttpStatus.INTERNAL_SERVER_ERROR);
    }
  }
}
